package com.xsound.dp15.bluetooothmonitor;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.xsound.dp15.bluetooothmonitor.custom.settimeDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_ENABLE_BT=1;
    private static final int REQUEST_ENABLE_BTFOUND=2;
    private static final int MAX_DISCOVERABLETIME=300;
    private static final String DEBUGDEVICENAME="devicename";
    private static final String DEBUGDEVICEADDR="deviceaddr";

    private ListView pairedDelist;
    private ListView unpairedDelist;
    private TextView pairedtxt;
    private TextView unpairedtxt;
    private android.support.v7.app.ActionBar bar;

    private SimpleAdapter mPsimAdapter=null;
    private SimpleAdapter mUPsimAdapter=null;
    private BluetoothAdapter mbluetoothAdapter=null;
    private IntentFilter filter=null;
    private List<Map<String, Object>> pairedList;
    private List<Map<String, Object>> unpairedList;
    private Set<BluetoothDevice> pairedDevices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.activity_main);
        //   ActionBar bar = getActionBar();
        bar=getSupportActionBar();
        //   bar.setLogo(R.mipmap.ic_launcher);
        bar.setIcon(R.mipmap.ic_launcher);
        //   bar.setDisplayUseLogoEnabled(true);
        bar.setDisplayShowHomeEnabled(true);
        bar.setSubtitle("not connected");

        pairedDelist=(ListView)findViewById(R.id.pairedlist);
        unpairedDelist=(ListView)findViewById(R.id.unpairedlist);
        pairedtxt=(TextView)findViewById(R.id.pairedTxt);
        unpairedtxt=(TextView)findViewById(R.id.unpairedTxt);

        mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


        pairedList=new ArrayList<Map<String,Object>>();
        unpairedList=new ArrayList<Map<String,Object>>();
        mPsimAdapter=new SimpleAdapter(this,pairedList,R.layout.mlistview,new String[]{"image","name","rssi","addr",
                "cod","other"},new int[]{R.id.imageView,R.id.devicename,R.id.devicerssi,R.id.deviceaddr,R.id.devicecod,R.id.other});
        mUPsimAdapter=new SimpleAdapter(this,unpairedList,R.layout.mlistview,new String[]{"image","name","rssi","addr",
                "cod","other"},new int[]{R.id.imageView,R.id.devicename,R.id.devicerssi,R.id.deviceaddr,R.id.devicecod,R.id.other});
        pairedDelist.setAdapter(mPsimAdapter);
        unpairedDelist.setAdapter(mUPsimAdapter);

        if(mbluetoothAdapter!=null){
            if (!mbluetoothAdapter.isEnabled()){
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, REQUEST_ENABLE_BT);
            }
        }else {
            Toast.makeText(MainActivity.this,"该设备不支持蓝牙",Toast.LENGTH_SHORT).show();
        }

        pairedDelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String devicename="";
                String deviceaddr="";
                if(mbluetoothAdapter.isDiscovering()){
                    mbluetoothAdapter.cancelDiscovery();
                }
                devicename=((TextView)view.findViewById(R.id.devicename)).getText().toString();
                deviceaddr=((TextView)view.findViewById(R.id.deviceaddr)).getText().toString();
                Intent intent=new Intent();
                intent.setClass(MainActivity.this, DebugActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString(DEBUGDEVICENAME,devicename);
                bundle.putString(DEBUGDEVICEADDR, deviceaddr);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        unpairedDelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String devicename="";
                String deviceaddr="";
                if(mbluetoothAdapter.isDiscovering()){
                    mbluetoothAdapter.cancelDiscovery();
                }
                devicename=((TextView)view.findViewById(R.id.devicename)).getText().toString();
                deviceaddr=((TextView)view.findViewById(R.id.deviceaddr)).getText().toString();
                Intent intent=new Intent();
                intent.setClass(MainActivity.this, DebugActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString(DEBUGDEVICENAME,devicename);
                bundle.putString(DEBUGDEVICEADDR, deviceaddr);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if((requestCode==REQUEST_ENABLE_BT)&&(resultCode==RESULT_OK)){
            Toast.makeText(MainActivity.this,"蓝牙开",Toast.LENGTH_SHORT).show();
            pairedDevices = mbluetoothAdapter.getBondedDevices();
            if (pairedDevices.size()> 0) {
                pairedtxt.setVisibility(View.VISIBLE);
                for (BluetoothDevice pdevice : pairedDevices) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("image",getcodId(pdevice.getBluetoothClass()));
                    map.put("name", pdevice.getName());
                    map.put("rssi", 0);
                    map.put("addr", pdevice.getAddress());
                    map.put("cod", pdevice.getBluetoothClass().getDeviceClass());
                    map.put("other", "已配对");
                    pairedList.add(map);
                }
                mPsimAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    //    return super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main_action_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
  //      return super.onOptionsItemSelected(item);
        switch (item.getItemId()){
            case R.id.action_search:
                searchDevice();
               // setProgressBarIndeterminateVisibility(true);
                return true;
            case R.id.action_open:
                if(!mbluetoothAdapter.isEnabled()){
                    BTon();
                    Toast.makeText(MainActivity.this,"打开蓝牙",Toast.LENGTH_SHORT).show();
                }
                return true;
            case R.id.action_discoverable:
//                handleSetDiscoverable();
            default:
                return true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            switch (action){
                case BluetoothDevice.ACTION_FOUND:
                    handleFound(intent);
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    handleSearchComplete();
                    break;
            }
        }
    };

    private void searchDevice(){
        if(mbluetoothAdapter!=null){
            if(mbluetoothAdapter.isEnabled()){
                if(!mbluetoothAdapter.isDiscovering()){
                    updateList();
                    mbluetoothAdapter.startDiscovery();
                    bar.setSubtitle("搜索中...");
                }else {

                }

            }else {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, REQUEST_ENABLE_BT);
            }

        }else{
            Toast.makeText(MainActivity.this,"该设备不支持蓝牙",Toast.LENGTH_SHORT).show();
        }
    }

    private void handleSetDiscoverable(){

//        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final settimeDialog dialog = new settimeDialog(MainActivity.this);
        dialog.show();
//        builder.setIcon(R.mipmap.ic_launcher);
//        builder.setTitle("请输入用户名和密码");

//        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.setdiscoverabletime_dialog, null);
//        dialog.setContentView(view);
        final EditText editText = (EditText)dialog.findViewById(R.id.timeTxt);
        Button setButton=(Button)dialog.findViewById(R.id.positiveButton);
        Button cancelButton=(Button)dialog.findViewById(R.id.negativeButton);
        setButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"确定按钮按下",Toast.LENGTH_SHORT).show();
                String timestr;
                int timenum;
                timestr=editText.getText().toString().trim();
                timenum=Integer.parseInt(timestr);
                if(timestr!="" && timenum>0 && timenum<=MAX_DISCOVERABLETIME){
                    Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    mIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, timenum);
                    startActivity(mIntent);
                }
            }
        });
//        cancelButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });


    }
    private void handleFound(Intent intent){
            unpairedtxt.setVisibility(View.VISIBLE);
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            int rssinum=intent.getIntExtra(BluetoothDevice.EXTRA_RSSI, 0);
            String name=intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
            BluetoothClass bluetoothClass=intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);

            Map<String, Object> map = new HashMap<>();
            map.put("image",getcodId(bluetoothClass));
            map.put("name", name);
            map.put("rssi", 0);
            map.put("addr", device.getAddress());
            map.put("cod", bluetoothClass.getDeviceClass());
            map.put("other", "未配对");
            unpairedList.add(map);
            mUPsimAdapter.notifyDataSetChanged();
    }

    private void handleSearchComplete(){
        bar.setSubtitle("搜索完成");
    }
    private void BTon(){
        mbluetoothAdapter.enable();
//      Toast.makeText(MainActivity.this,"打开蓝牙",Toast.LENGTH_SHORT).show();
    }

    private void enableDiscoverable(){
        Intent intent=new Intent(mbluetoothAdapter.ACTION_REQUEST_DISCOVERABLE );
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);
        startActivityForResult(intent,REQUEST_ENABLE_BTFOUND);
    }

    private void updateList(){
        pairedList.clear();
        pairedDevices = mbluetoothAdapter.getBondedDevices();
        if (pairedDevices.size()> 0) {
            pairedtxt.setVisibility(View.VISIBLE);
            for (BluetoothDevice pdevice : pairedDevices) {
                Map<String, Object> map = new HashMap<>();
                map.put("image",getcodId(pdevice.getBluetoothClass()));
                map.put("name", pdevice.getName());
                map.put("rssi", 0);
                map.put("addr", pdevice.getAddress());
                map.put("cod", pdevice.getBluetoothClass().getDeviceClass());
                map.put("other", "已配对");
                pairedList.add(map);
            }
            mPsimAdapter.notifyDataSetChanged();
        }
    }

    private int getcodId(BluetoothClass deviceclass){
        int devicecod=deviceclass.getDeviceClass();
        switch (devicecod){
            case BluetoothClass.Device.COMPUTER_DESKTOP:
                return R.drawable.desktop;
            case BluetoothClass.Device.COMPUTER_LAPTOP:
                return R.drawable.laptop;
            case BluetoothClass.Device.PHONE_SMART:
                return R.drawable.smartphone;
            case BluetoothClass.Device.PHONE_CELLULAR:
                return R.drawable.phone;
            case BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES:
                return R.drawable.headset;
            case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
                return R.drawable.headset;
            default:
                return R.drawable.headset;
        }
    }
}
